package com.enpronomics.pcall.receivers;

import java.lang.reflect.Method;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.media.AudioManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;

import com.android.internal.telephony.ITelephony;
import com.enpronomics.pcall.MyLocation;
import com.enpronomics.pcall.MyLocation.LocationResult;
import com.enpronomics.pcall.ServiceManager;

public class PhoneCallReceiver extends BroadcastReceiver {

	private Context context;
	private String incomingNumber;
	private ITelephony telephonyService;

	private AudioManager am;
	private int ringingMode;

	private String getPhoneNo() {
		return ServiceManager.getStringSetting(context,
				ServiceManager.KEY_AUTO_ASSISTANCE_NUMBER).replaceAll("-", "");
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		this.context = context;

		String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
		echo("Phone State: " + state);
		
		incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
		echo("Phone Number: " + incomingNumber);
		if (isRinging()
				&& incomingNumber.replaceAll("-", "").equals(getPhoneNo())
				&& ServiceManager.getBoolSetting(context,
						ServiceManager.KEY_AUTO_ASSISTANCE)) {//
		// if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
			echo("Recieving the call (new20)");
			am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
			ringingMode = am.getRingerMode();
			am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
			answerCall();
			sendSMS();
		}
		else if(state.equals(TelephonyManager.EXTRA_STATE_IDLE)
//			&&incomingNumber.replaceAll("-", "").equals(ServiceManager.getStringSetting(context,ServiceManager.KEY_PANIC_CALL_NUMBER).replaceAll("-", ""))
			&&ServiceManager.getBoolSetting(context,ServiceManager.PANIC_INITIATED)){
				ServiceManager.setBoolSetting(context,ServiceManager.PANIC_INITIATED,false);
		}
	}

	private void answerPhoneHeadsethook() {
		echo("Still answering");
		try {
			echo("adding headset");
			Intent headSetUnPluggedintent = new Intent(
					Intent.ACTION_HEADSET_PLUG);
			headSetUnPluggedintent
					.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
			headSetUnPluggedintent.putExtra("state", 1);
			headSetUnPluggedintent.putExtra("name", "Headset");
			context.sendOrderedBroadcast(headSetUnPluggedintent, null);

			// Simulate a press of the headset button to pick up the call
			// Intent buttonDown = new Intent(Intent.ACTION_MEDIA_BUTTON);
			// buttonDown.putExtra(Intent.EXTRA_KEY_EVENT, new
			// KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK));
			// context.sendOrderedBroadcast(buttonDown,
			// "android.permission.CALL_PRIVILEGED");
			// echo("Button is down");

			// froyo and beyond trigger on buttonUp instead of buttonDown
			Intent buttonUp = new Intent(Intent.ACTION_MEDIA_BUTTON);
			buttonUp.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(
					KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
			context.sendOrderedBroadcast(buttonUp,
					"android.permission.CALL_PRIVILEGED");
			echo("Button is up");

			echo("removing headset");
			headSetUnPluggedintent = new Intent(Intent.ACTION_HEADSET_PLUG);
			headSetUnPluggedintent
					.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
			headSetUnPluggedintent.putExtra("state", 0);
			headSetUnPluggedintent.putExtra("name", "Headset");
			context.sendOrderedBroadcast(headSetUnPluggedintent, null);

			Thread.sleep(2000);
			am.setRingerMode(ringingMode);
		} catch (Exception e) {
			echo("Error:" + e.toString());
		}
	}

	private boolean isRinging() {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		try {
			echo("Get getTeleService...");
			Class c = Class.forName(tm.getClass().getName());
			Method m = c.getDeclaredMethod("getITelephony");
			m.setAccessible(true);
			telephonyService = (ITelephony) m.invoke(tm);

			return telephonyService.isRinging();

		} catch (Exception e) {
			echo("Error in accessing Telephony Manager: " + e.toString());
			telephonyService = null;
		}

		return false;
	}

	private void cancelCall() {
		echo("Ending call..." + incomingNumber);
		try {
			if (telephonyService != null)
				telephonyService.endCall();
		} catch (Exception e) {
			e.printStackTrace();
			echo("Error in accessing Telephony Manager: " + e.toString());
		}
	}

	private void answerCall() {
		echo("Answering call..." + incomingNumber);
		try {
			if (telephonyService != null) {
				telephonyService.answerRingingCall();
				echo("Call is answered");
			} else
				echo("Telephone Service=null");
		} catch (Exception e) {
			e.printStackTrace();
			echo("Error in accessing Telephony Manager: " + e.toString());
			answerPhoneHeadsethook();
		}
	}

	private void sendSMS() {
		echo("Getting Location");
		new MyLocation().init(context, locationResult);
		// SmsManager.getDefault().sendTextMessage(incomingNumber, null,
		// getSMSBody(), null, null);
		// Log.v("-------------", "SMS sent");
		// Toast.makeText(context, "SMS Sent", Toast.LENGTH_LONG).show();
	}

	public LocationResult locationResult = new LocationResult() {
		@Override
		public void gotLocation(final Location location) {
			String locationStr;
			if (location == null)
				locationStr = "No location Found";
			else
				locationStr = ServiceManager.getLocationStr(location);

			echo("Sending sms");
			ServiceManager.sendSMS(
					null,
					ServiceManager.getStringSetting(context,
							ServiceManager.KEY_PANIC_SMS_NUMBER),
					ServiceManager.PANIC_MESSAGE + ";" + locationStr + ";"
							+ ServiceManager.KEY_NAME + ";"
							+ ServiceManager.getCurrentDate());
			echo("SMS sent");
		}
	};

	private void echo(String s) {
		Log.d("------pCall-------", s);
		// Toast.makeText(context, s, Toast.LENGTH_LONG).show();
	}
}
